﻿using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AutoMapper;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using netCoreStudy.Dto.User;
using netCoreStudy.Entities;
using netCoreStudy.Entities.Base;
using netCoreStudy.Entities.Parameter;
using netCoreStudy.Enum;
using netCoreStudy.IService;

namespace netCoreStudy.Controllers
{
	/// <summary>
	/// 用户管理 
	/// </summary>
	[ApiController]
	[Route("api/role")]
	public class RoleController : BaseController<Role, RoleDto, RoleParameter, AddRoleDto, UpdateRoleDto>
	{
		private readonly IRoleService _roleService;

		public RoleController(ILogger<RoleController> logger, IBaseService<Role> baseService, IMapper mapper,
			IRoleService roleService)
			: base(logger, baseService, mapper)
		{
			_roleService = roleService;
		}

		/// <summary>
		/// 写 AllowAnonymous 代表不用token也可以访问 
		/// </summary>
		/// <param name="ids"></param>
		/// <returns></returns>
		[AllowAnonymous]
		public override Task<IActionResult> GetByIds(long[] ids)
		{
			return base.GetByIds(ids);
		}

		protected override RoleDto AfterGetOne(RoleDto dto)
		{
			List<MenuDtoSm> menuDtoSms = dto.Menus.Where(x => x.PId == 0).ToList();
			foreach (MenuDtoSm menuDtoSm in menuDtoSms)
			{
				GetMenus(menuDtoSm, dto.Menus);
			}

			dto.Menus = menuDtoSms;
			return dto;
		}

		/// <summary>
		/// 添加一个role 角色 ，原来 的 没法用…… 
		/// </summary>
		/// <param name="addDto"></param>
		/// <returns></returns>
		[HttpPost("post")]
		public async Task<IActionResult> AddRole(AddRoleDto addDto)
		{
			Role tEntity = _mapper.Map<Role>(addDto);
			_baseService.Add(tEntity);
			await _baseService.SaveAsync();
			RoleDto tDto = _mapper.Map<RoleDto>(tEntity);

			return this.SuccessMsg("添加角色成功", tDto);
		}

		/// <summary>
		/// 递归获取menu 
		/// </summary>
		/// <param name="menuDtoSm"></param>
		/// <param name="dtoMenus"></param>
		private void GetMenus(MenuDtoSm menuDtoSm, List<MenuDtoSm> dtoMenus)
		{
			List<MenuDtoSm> menuDtoSms = dtoMenus.Where(x => x.PId == menuDtoSm.Id).ToList();
			menuDtoSm.Children.AddRange(menuDtoSms);
			foreach (MenuDtoSm dtoSm in menuDtoSms)
			{
				GetMenus(dtoSm, dtoMenus);
			}
		}
	}
}